<?php

namespace App\Admin\Repositories;

use App\Admin\Contracts\MemberInterface;
use App\Admin\Exceptions\MemberException;
use App\Admin\Models\ConfigModel;
use App\Admin\Models\MemberModel;
use App\Admin\Models\UcenterMemberModel;
use App\Base\Helpers\Lib\GoogleAuthenticator;
use App\Base\Repositories\DbBaseRepository;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Request;


/**
 * Created by 荣耀电竞.
 * User: 林子彦 <278805354@qq.com>
 * Date: 2018/5/17 0017
 * Time: 17:22
 */
class DbMemberRepository implements MemberInterface
{
    /**
     * 用户表
     * @return MemberModel
     */
    public function getMemberModel()
    {
        return app()->make(MemberModel::class);
    }

    /**
     * 用户中心表
     * @return UcenterMemberModel
     */
    public function getUcenterMemberModel()
    {
        return app()->make(UcenterMemberModel::class);
    }

    /**
     * 用户登陆授权
     * @param $data
     * @return mixed
     * @throws MemberException
     */
    public function login($data)
    {
        $ucenterMemberInfo = $this->getUcenterMemberModel()->newQuery()->with(["member"])->where("username", $data["username"])->first();
        if (!$ucenterMemberInfo) {
            throw new MemberException(MemberException::EROOR_MEMBER_LOGIN_USER_NOT);
        }
        if ($ucenterMemberInfo->status == 0) {
            throw new MemberException(MemberException::EROOR_MEMBER_LOGIN_STATUS_DISABLE);
        }
        if ($ucenterMemberInfo->status == 0) {
            throw new MemberException(MemberException::EROOR_MEMBER_LOGIN_STATUS_DISABLE);
        }
        if ($ucenterMemberInfo->status == -1) {
            throw new MemberException(MemberException::EROOR_MEMBER_LOGIN_DELELTE);
        }
        $password = $data["password"];

        if ($ucenterMemberInfo->password !== lqw_ucenter_md5($password, config("lzy.DATA_AUTH_KEY"))) {
            throw new MemberException(MemberException::EROOR_MEMBER_LOGIN_PASSWORD);
            return false;
        }
        //判断是否是google 认证
        $check_otp = get_config_param_value("BACKEND_SWITCH_OTP");
        if ($check_otp) {

            session([
                'lqwsys_member_username' => $ucenterMemberInfo->username
            ]); // 存到session中
            //判断会员验证是否为空
            session()->save();
            if (empty($ucenterMemberInfo->member->otp_gg)) {
                throw new MemberException(MemberException::EROOR_OPT_RE_URL); //跳转到绑定页面
            }
            $vercode=$data["vercode"];
            if (empty($vercode)) {
                throw new MemberException(MemberException::EROOR_OPT_EMPTY_CODE); //验证码不能为空
            }
            $otpGg=$this->getGoogleCode($ucenterMemberInfo->member->otp_gg);
            if ($otpGg != $data['vercode']) {
                throw new MemberException(MemberException::EROOR_OPT_CODE);//OTP验证码错误
            }
        }

        $this->update($ucenterMemberInfo);//更新用户信息
        $remember=empty($data["remember"])?'':$data["remember"];
        if($remember=='on'){  //如果打开记住密码，则放到cookie中去
           $this->setLoginCookie($ucenterMemberInfo);
        }
        return $ucenterMemberInfo;
    }

    /**
     * 记住密码操作
     * @param $ucenterMemberInfo
     */
    public function setLoginCookie($ucenterMemberInfo){
        $auth = array(
            'uid' => $ucenterMemberInfo->id,
            'username' => $ucenterMemberInfo->username,
            'nickname' => $ucenterMemberInfo->member->nickname,
            'logo' => $ucenterMemberInfo->member->logo
        );
        $cookies_expire =3600 * 24 * 365;  //cookie 进期时间
        Cookie::queue('admin_uid', $ucenterMemberInfo->id, $cookies_expire);  //用户id
        Cookie::queue('admin_username', $ucenterMemberInfo->username, $cookies_expire); //用户名
        Cookie::queue('admin_nickname',$ucenterMemberInfo->member->nickname, $cookies_expire); //用户昵称
        Cookie::queue('admin_logo',  $ucenterMemberInfo->member->logo, $cookies_expire);    //用户头像
        Cookie::queue('lqwsys_auth_sign',data_auth_sign($auth), $cookies_expire);    //加密串
    }

    public function update($ucenterMemberInfo)
    {
        // 用户行为操作
        $auth = array(
            'uid' => $ucenterMemberInfo->id,
            'username' => $ucenterMemberInfo->username,
            'nickname' => $ucenterMemberInfo->member->nickname,
            'logo' => $ucenterMemberInfo->member->logo
        );
        // session(['lqwsys_auth'=> $auth]); //存到session中
        session([
            'lqwsys_auth' => $auth
        ]);
        session([
            'lqwsys_auth_sign' => data_auth_sign($auth)
        ]); // 存到session中
        session()->save();

        //登陆记录到登陆表中去
        action_log("user_login", "Member", $ucenterMemberInfo->id, $ucenterMemberInfo->id);
    }

    /**
     * 用户列表数据集
     * @param $where 条件
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getMemberList($where)
    {
        $request = Request::instance();
        $limit = empty($request->input("limit")) ? 10 : $request->input("limit");
        return $this->getMemberModel()->newQuery()->where($where)->paginate($limit);
    }

    /**
     * 用户信息
     * @param $where
     * @return \Illuminate\Database\Eloquent\Model|mixed|null|object|static
     */
    public function getMemberInfo($where)
    {
        return $this->getMemberModel()->newQuery()->where($where)->first();
    }

    /**
     * 数据新增与更新
     * @param $data
     * @return mixed|void
     */
    public function saveMemberData($data)
    {
        $data = $this->getMemberModel()->filter($data);
        return $this->getMemberModel()->newQuery()->where("uid", $data["uid"])->update($data);
    }

    /**
     * 数据新增与更新
     * @param $data
     * @return mixed|void
     */
    public function addUcenterMemberData($data)
    {
        $data = $this->getUcenterMemberModel()->filter($data);
        return $this->getUcenterMemberModel()->newQuery()->create($data);
    }

    /**
     * 根据条件获取某字段
     * @param $where
     * @param $field
     * @return \Illuminate\Support\Collection
     */
    public function getUcenterMemberFindFiled($where, $field)
    {
        return $this->getUcenterMemberModel()->newQuery()->where($where)->pluck($field);
    }

    /**
     * 获取用户信息
     * @param $where
     * @return \Illuminate\Database\Eloquent\Model|null|object|static
     */
    public function getUcnterMemberInfo($where)
    {
        return $this->getUcenterMemberModel()->newQuery()->where($where)->first();
    }

    /**
     * 删除用户信息
     * @param $where
     * @return mixed
     * @throws MemberException
     */
    public function delMember($where)
    {
        if (is_administrator($where["uid"])) {
            throw  new MemberException(MemberException::EROOR_MEMBER_ADMINISTARTOR_OPTION_ERROR);
        }
        $this->getUcenterMemberModel()->newQuery()->where(["id" => $where["uid"]])->delete();
        return $this->getMemberModel()->newQuery()->where($where)->delete();
    }

    /**
     * 新增一条用户信息
     * @param $data
     * @return mixed|void
     */
    public function addMemberInfoRow($data)
    {
        $password = $data["password"];
        $repassword = $data["repassword"];
        if ($password !== $repassword) {
            throw  new MemberException(MemberException::EROOR_MEMBER_SAVE_PASSWORD_SAME);
        }
        //判断帐号是否存在
        if (!$this->getUcenterMemberFindFiled(["username" => $data["username"]], "username")->isEmpty()) {
            throw  new MemberException(MemberException::EROOR_MEMBER_ACCOUNT_ISEXIT);
        }
        //判断手机号是否存在
        if (!$this->getUcenterMemberFindFiled(["mobile" => $data["mobile"]], "mobile")->isEmpty()) {
            throw  new MemberException(MemberException::EROOR_MEMBER_MOBILE_ISEXIT);
        }
        $udata = array();
        $udata["username"] = $data["username"];
        $udata["password"] = lqw_ucenter_md5($password, config("lzy.DATA_AUTH_KEY"));
        $udata["mobile"] = $data["mobile"];
        $udata["reg_time"] = time();
        $udata["reg_ip"] = getClientIp(1);
        if ($turn_data = $this->addUcenterMemberData($udata)) {
            $mdata = array();
            $mdata["uid"] = $turn_data->id;
            $mdata["nickname"] = $data["nickname"];
            $mdata["logo"] = $data["logo"];
            $mdata["sex"] = empty($data["sex"]) ? 0 : 1;
            $mdata["birthday"] = $data["birthday"];
            return $this->addMemberData($mdata);
        } else {
            throw new MemberException(MemberException::EROOR_MEMBER_SAVE);
        }
    }

    /**
     * 更新用户信息
     * @param $data
     * @return mixed|void
     */
    public function updateMemberInfoRow($data)
    {

        $password = $data["password"];
        $where = function ($query) use ($data) {
            $query->where("username", $data["username"]);
            $query->where("id", "<>", $data["id"]);
        };
        //判断帐号是否存在
        if (!$this->getUcenterMemberFindFiled($where, "username")->isEmpty()) {
            throw  new MemberException(MemberException::EROOR_MEMBER_ACCOUNT_ISEXIT);
        }
        $where = function ($query) use ($data) {
            $query->where("mobile", $data["mobile"]);
            $query->where("id", "<>", $data["id"]);
        };
        //判断手机号是否存在
        if (!$this->getUcenterMemberFindFiled($where, "mobile")->isEmpty()) {
            throw  new MemberException(MemberException::EROOR_MEMBER_MOBILE_ISEXIT);
        }

        $udata = array();
        $udata["username"] = $data["username"];
        if (!empty($password)) {
            $udata["password"] = lqw_ucenter_md5($password, config("lzy.DATA_AUTH_KEY"));
        }
        $udata["mobile"] = $data["mobile"];
        $udata["reg_time"] = time();
        $udata["reg_ip"] = getClientIp(1);
        if ($this->updateUcenterMember(["id" => $data["id"]], $udata)) {
            $mdata = array();
            $mdata["nickname"] = $data["nickname"];
            $mdata["logo"] = $data["logo"];
            $mdata["sex"] = empty($data["sex"]) ? 0 : 1;
            $mdata["birthday"] = $data["birthday"];
            //清去用户缓存
            Cache::forget("member:ucentermeber:user_accout_" . $data["id"]);
            return $this->updateMember(["uid" => $data["id"]], $mdata);
        } else {
            throw new MemberException(MemberException::EROOR_MEMBER_SAVE);
        }
    }

    /**
     * 更新用户信息
     * @param $where
     * @param $data
     * @return int|mixed
     */
    public function updateMember($where, $data)
    {
        return $this->getMemberModel()->newQuery()->where($where)->update($data);
    }

    /**
     * 更新用户中心
     * @param $where
     * @param $data
     * @return int
     */
    public function updateUcenterMember($where, $data)
    {
        return $this->getUcenterMemberModel()->newQuery()->where($where)->update($data);
    }

    /**
     * 保存用户基本信息
     * @param $data
     * @return $this|\Illuminate\Database\Eloquent\Model
     */
    public function addMemberData($data)
    {
        $data = $this->getMemberModel()->filter($data);
        return $this->getMemberModel()->newQuery()->create($data);
    }

    /**
     * 根据uid获取帐号
     * @param $uid
     */
    public function getAccountByUid($uid)
    {
        $user_accout = Cache::remember('member:ucentermeber:user_accout_' . $uid, 3600, function () use ($uid) {
            return $this->getUcenterMemberModel()->newQuery()->where("id", $uid)->pluck("username");
        });
        return $user_accout ?? '';
    }

    /**
     * 根据帐号获取uid
     * @param $account
     * @return mixed|string
     */
    public function getUidByAccount($account)
    {
        $uid = Cache::remember('member:ucentermeber:user_uid_' . $account, 3600, function () use ($account) {
            return $this->getUcenterMemberModel()->newQuery()->where("username", $account)->pluck("id");
        });
        return $uid ?? '';
    }


    /**
     * 根据帐号获取uid
     * @param $account
     * @return mixed|string
     */
    public function getMobileByUid($uid)
    {
        //$mobile = Cache::remember('member:ucentermeber:user_mobile_' . $uid, 3600, function () use ($uid) {
            return $this->getUcenterMemberModel()->newQuery()->where("id", $uid)->value("mobile");
        //});
      // return $mobile ?? '';
    }

    /**
     * 获取模型
     * @param $model
     * @return bool|mixed
     */
    public function optionModle($model)
    {
        $rules_string = "App\Base\Contracts\ActionInterface";
        if (interface_exists($rules_string) || class_exists($rules_string)) {
            $makeClass = app()->make($rules_string);
            echo "bbbbb";
        } else {
            return false;
        }
        exit;
    }

    /**
     * 更新密码
     * @param $data
     * @return mixed|void
     */
    public function updatePassword($data)
    {
        $memberInfo = $this->getUcenterMemberModel()->newQuery()->where("id", $data["uid"])->first();

        if (empty($memberInfo)) {
            throw new MemberException(MemberException::EROOR_MEMBER_LOGIN_USER_NOT);
        }

        //判断原来密码是否正确
        if ($memberInfo->password != lqw_ucenter_md5($data['oldpassword'], config("lzy.DATA_AUTH_KEY"))) {
            throw new MemberException(MemberException::EROOR_MEMBER_LOGIN_PASSWORD);
        }
        //更新密码
        return $this->getUcenterMemberModel()->newQuery()->where(["id" => $data['uid']])->update(['password' => lqw_ucenter_md5($data['password'], config("lzy.DATA_AUTH_KEY"))]);
    }

    /**
     * 修改用户状态
     * @param $data
     */
    public function changeStatus($data)
    {

        //如果是超级管员无法关闭
        if ((intval($data["uid"]) == (int)is_administrator())) {
            throw  new MemberException(MemberException::EROOR_MEMBER__STATUS_ISADMIN);
        }
        if ($this->getUcenterMemberModel()->newQuery()->where("id", $data["uid"])->update(["status" => $data['status']])) {
            return $this->getMemberModel()->newQuery()->where("uid", $data["uid"])->update(["status" => $data["status"]]);
        } else {
            throw  new MemberException(MemberException::EROOR_MEMBER_CHANGE_STATUS);
        }
    }


    /**
     * 获取验证码
     * @param $code
     * @return string
     */
    public function getGoogleCode($code){
        $ga = new GoogleAuthenticator();
        $oneCode = $ga->getCode($code); //服务端计算"一次性验证码"
        return $oneCode;
    }

    /**
     * 获取邦定串
     * @return string
     */
    public function getGoogleSecret(){
        $ga = new GoogleAuthenticator();
        //创建一个新的"安全密匙SecretKey"
        //把本次的"安全密匙SecretKey" 入库,和账户关系绑定,客户端也是绑定这同一个"安全密匙SecretKey"
        $secret = $ga->createSecret();
        return $secret;

    }

    /**
     * 更新google二维码
     * @param $data
     * @return int|mixed
     * @throws MemberException
     */
    public function bindGoogleOtp($data){

        $username = session('lqwsys_member_username');  //登陆用户名
        if(empty($username)){
            throw  new MemberException(MemberException::EROOR_MEMBER_LOGIN_USER_NOT);
        }
        //然后加上
        $uMemberInfo=$this->getUcenterMemberModel()->newQuery()->where("username",$username)->first();
        if(empty($uMemberInfo)){
            throw new MemberException(MemberException::EROOR_MEMBER_LOGIN_USER_NOT);
        }
        //更新邦定
        return $this->getMemberModel()->newQuery()->where("uid",$uMemberInfo->id)->update(["otp_gg"=>$data['secret']]);
    }

    /***
     * 根据和件获取用户信息
     * @param $where
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|mixed|null|object
     */
    public function findUcenterMember($where){
        return $this->getUcenterMemberModel()->newQuery()->where($where)->first();
    }

    /**
     * 前端获取openid
     * @param $uid
     * @return mixed
     */
    public function getOpenIdByUid($uid){
        return $this->getUcenterMemberModel()->newQuery()->where("id",$uid)->value("username");
    }


}